#include "RobotClient.h"
#include "DisconnectLogger.h"
#include <QDateTime>

RobotClient::RobotClient(QTcpSocket *socket, QObject *parent)
    : QObject(parent), m_socket(socket), m_isRegistered(false), m_networkErrorCount(0), m_packetLog(nullptr), m_connectionStartTime(0)
{
    m_socket->setParent(this);
    
    // 获取服务器地址和端口，添加有效性检查
    QString peerAddress = m_socket->peerAddress().toString();
    int peerPort = m_socket->peerPort();
    
    qDebug() << QString("RobotClient构造函数 - 原始地址信息: %1:%2").arg(peerAddress).arg(peerPort);
    
    // 处理IPv6映射的IPv4地址
    if (peerAddress.startsWith("::ffff:")) {
        peerAddress = peerAddress.mid(7);  // 移除"::ffff:"前缀
        qDebug() << QString("RobotClient构造函数 - 处理IPv6映射地址后: %1").arg(peerAddress);
    }
    
    // 验证地址有效性并缓存
    if (!peerAddress.isEmpty() && peerAddress != ":0" && peerAddress != "0.0.0.0") {
        m_serverAddress = peerAddress;
        m_cachedClientAddress = peerAddress;  // 缓存有效地址
        qDebug() << QString("RobotClient构造函数 - 有效服务器地址: %1").arg(m_serverAddress);
    } else {
        m_serverAddress = "";  // 设置为空，表示地址无效
        qDebug() << QString("警告：RobotClient构造时获取到无效的服务器地址: %1:%2").arg(peerAddress).arg(peerPort);
    }
    
    m_serverPort = peerPort;
    
    // 记录连接开始时间
    m_connectionStartTime = QDateTime::currentMSecsSinceEpoch();
    
    // 初始化数据包日志记录
    initializePacketLog();
    
    // 创建心跳定时器
    m_heartbeatTimer = new QTimer(this);
    m_heartbeatTimer->setSingleShot(true);
    m_heartbeatTimer->setInterval(HEARTBEAT_TIMEOUT);
    
    // 创建网络状态检查定时器（但不启动它）
    m_networkCheckTimer = new QTimer(this);
    m_networkCheckTimer->setSingleShot(false);
    // m_networkCheckTimer->setInterval(NETWORK_CHECK_INTERVAL);
    
    // 创建注册超时定时器
    m_registerTimeoutTimer = new QTimer(this);
    m_registerTimeoutTimer->setSingleShot(true);
    m_registerTimeoutTimer->setInterval(REGISTER_TIMEOUT);
    
    // 创建异步日志刷新定时器
    m_logFlushTimer = new QTimer(this);
    m_logFlushTimer->setSingleShot(false);
    m_logFlushTimer->setInterval(5000); // 5秒刷新一次日志
    connect(m_logFlushTimer, &QTimer::timeout, this, &RobotClient::flushLogQueue);
    
    // 连接socket信号
    connect(m_socket, &QTcpSocket::readyRead, this, &RobotClient::onReadyRead);
    connect(m_socket, &QTcpSocket::disconnected, this, &RobotClient::onDisconnected);
    // 恢复错误信号连接，实现网络错误处理流程
    connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),
            this, &RobotClient::onErrorOccurred);
    
    // 连接心跳定时器
    connect(m_heartbeatTimer, &QTimer::timeout, this, &RobotClient::onHeartbeatTimeout);
    
    // 连接网络状态检查定时器（但不启动它）
    // connect(m_networkCheckTimer, &QTimer::timeout, this, &RobotClient::checkNetworkStatus);
    
    // 连接注册超时定时器
    connect(m_registerTimeoutTimer, &QTimer::timeout, this, &RobotClient::onRegisterTimeout);
    
    // 启动心跳监控（但不启动网络检查）
    startHeartbeatTimer();
    // startNetworkCheckTimer();
    
    // 启动注册超时检查（仅对未注册设备）
    startRegisterTimeoutTimer();
    
    // 启动日志刷新定时器
    m_logFlushTimer->start();
}

RobotClient::~RobotClient()
{
    stopHeartbeatTimer();
    stopNetworkCheckTimer();
    stopRegisterTimeoutTimer();
    
    // 停止日志刷新定时器
    if (m_logFlushTimer) {
        m_logFlushTimer->stop();
    }
    
    // 清空日志队列
    QMutexLocker locker(&m_logMutex);
    m_logQueue.clear();
    
    // 关闭数据包日志文件
    if (m_packetLog && m_packetLog->isOpen()) {
        m_packetLog->close();
    }
    delete m_packetLog;
}

QString RobotClient::getClientAddress() const
{
    QString address = m_socket->peerAddress().toString();
    int port = m_socket->peerPort();
    
    qDebug() << QString("获取客户端地址信息: 原始地址=%1, 端口=%2").arg(address).arg(port);
    
    // 处理IPv6映射的IPv4地址
    if (address.startsWith("::ffff:")) {
        address = address.mid(7);  // 移除"::ffff:"前缀
        qDebug() << QString("处理IPv6映射地址后: %1").arg(address);
    }
    
    // 验证IP地址有效性
    // 检查是否为空、是否为":0"、是否为"0.0.0.0"、是否包含"::"、长度是否小于7
    if (address.isEmpty() || address == ":0" || address == "0.0.0.0" || 
        address.contains("::") || address.length() < 7) {
        // 如果当前无法获取有效地址，但有缓存地址，则使用缓存地址
        if (!m_cachedClientAddress.isEmpty()) {
            qDebug() << QString("使用缓存的客户端IP地址: %1").arg(m_cachedClientAddress);
            return m_cachedClientAddress;
        }
        
        qDebug() << QString("警告：获取到无效的客户端IP地址: %1，端口: %2").arg(address).arg(port);
        return "";  // 返回空字符串而不是无效地址
    }
    
    // 注意：不能在const函数中修改成员变量
    // m_cachedClientAddress = address;  // 这会导致编译错误
    
    return address;
}

int RobotClient::getClientPort() const
{
    return m_socket->peerPort();
}

QString RobotClient::getRobotSN() const
{
    return m_robotSN;
}

bool RobotClient::isRegistered() const
{
    return m_isRegistered;
}

bool RobotClient::isConnected() const
{
    // 恢复socket状态检查
    QAbstractSocket::SocketState state = m_socket->state();
    bool socketConnected = (state == QAbstractSocket::ConnectedState);
    bool hasValidAddress = !m_cachedClientAddress.isEmpty();
    
    qDebug() << QString("RobotClient::isConnected() 检查连接状态，SN: %1, 状态: %2, 状态描述: %3, Socket连接: %4, 有效地址: %5")
                .arg(m_robotSN)
                .arg(state)
                .arg(socketStateToString(state))
                .arg(socketConnected)
                .arg(hasValidAddress);
    
    // 如果socket未连接，但有缓存的有效地址，可能处于短暂断开状态但仍可通信
    // 在这种情况下，我们仍然认为连接是有效的
    return socketConnected || (m_isRegistered && hasValidAddress);
}

void RobotClient::disconnectFromHost()
{
    stopHeartbeatTimer();
    // 恢复socket状态检查
    if (m_socket->state() != QAbstractSocket::UnconnectedState) {
        m_socket->disconnectFromHost();
    }
}

void RobotClient::sendMessage(const QJsonObject &message)
{
    // 恢复socket状态检查
    if (m_socket->state() != QAbstractSocket::ConnectedState) {
        return;
    }
    
    QJsonDocument doc(message);
    QByteArray data = doc.toJson(QJsonDocument::Compact) + "\n";
    m_socket->write(data);
}

void RobotClient::onReadyRead()
{
    QByteArray newData = m_socket->readAll();
    // 减少不必要的调试日志输出
    // qDebug() << "RobotClient::onReadyRead() 接收到数据:" << newData;
    
    // 记录原始数据包到日志文件
    logPacket(newData);
    
    m_buffer.append(newData);
    
    // 处理缓冲区中的消息（以换行符分隔）
    while (m_buffer.contains('\n')) {
        int pos = m_buffer.indexOf('\n');
        QByteArray messageData = m_buffer.left(pos);
        m_buffer.remove(0, pos + 1);
        
        if (!messageData.isEmpty()) {
            // 减少不必要的调试日志输出
            // qDebug() << "RobotClient::onReadyRead() 处理消息数据:" << messageData;
            
            // 处理可能粘连的多个JSON对象
            QList<QByteArray> jsonObjects;
            int braceCount = 0;
            int startPos = 0;
            
            for (int i = 0; i < messageData.size(); i++) {
                if (messageData[i] == '{') {
                    if (braceCount == 0) {
                        startPos = i;  // 记录JSON对象开始位置
                    }
                    braceCount++;
                } else if (messageData[i] == '}') {
                    braceCount--;
                    if (braceCount == 0) {
                        // 提取完整的JSON对象
                        QByteArray jsonObject = messageData.mid(startPos, i - startPos + 1);
                        jsonObjects.append(jsonObject);
                    }
                }
            }
            
            // 处理提取出的JSON对象
            for (const QByteArray &jsonObject : jsonObjects) {
                // qDebug() << "RobotClient::onReadyRead() 处理JSON对象:" << jsonObject;
                
                QJsonParseError parseError;
                QJsonDocument doc = QJsonDocument::fromJson(jsonObject, &parseError);
                
                if (parseError.error == QJsonParseError::NoError && doc.isObject()) {
                    QJsonObject message = doc.object();
                    processMessage(message);
                } else {
                    QString errorMsg = parseError.errorString();
                    QString clientIp = getClientAddress();
                    qDebug() << QString("JSON解析错误: %1, 客户端IP: %2, 原始数据: %3").arg(errorMsg).arg(clientIp).arg(QString(jsonObject));
                    
                    // 发送JSON解析错误信号
                    emit jsonParseError(clientIp, QString(jsonObject), errorMsg);
                }
            }
        }
    }
}

void RobotClient::onDisconnected()
{
    // 计算连接持续时间
    qint64 connectionDuration = 0;
    if (m_connectionStartTime > 0) {
        connectionDuration = QDateTime::currentMSecsSinceEpoch() - m_connectionStartTime;
    }
    
    // 记录详细断开连接日志
    QString reason = "客户端主动断开";
    if (m_socket) {
        QAbstractSocket::SocketError error = m_socket->error();
        if (error != QAbstractSocket::UnknownSocketError) {
            reason = QString("网络错误: %1").arg(m_socket->errorString());
        }
    }
    
    DisconnectLogger::instance()->logDisconnect(
        DisconnectType::UserRequest,
        reason,
        "",
        m_robotSN,
        getClientAddress(),
        getClientPort(),
        DisconnectResult::Success,
        QString("连接持续时间: %1ms, 注册状态: %2, 网络错误计数: %3")
            .arg(connectionDuration)
            .arg(m_isRegistered ? "已注册" : "未注册")
            .arg(m_networkErrorCount)
    );
    
    qDebug() << QString("机器人客户端断开连接: %1 (SN: %2)").arg(getClientAddress()).arg(m_robotSN);
    stopHeartbeatTimer();
    
    // 停止所有定时器
    stopRegisterTimeoutTimer();
    
    // 发送断开连接信号
    emit disconnected();
}

void RobotClient::onErrorOccurred(QAbstractSocket::SocketError error)
{
    // 增强错误处理逻辑，实现网络错误处理流程
    QString errorString = m_socket->errorString();
    QAbstractSocket::SocketState state = m_socket->state();
    
    qDebug() << QString("机器人客户端错误: %1 (错误码: %2, 状态: %3)").arg(errorString).arg(error).arg(socketStateToString(state));
    
    // 根据错误类型进行分类处理，仅记录错误，不触发重连
    switch (error) {
        case QAbstractSocket::ConnectionRefusedError:
        case QAbstractSocket::RemoteHostClosedError:
        case QAbstractSocket::HostNotFoundError:
        case QAbstractSocket::SocketTimeoutError:
            // 网络连接错误，增加错误计数
            m_networkErrorCount++;
            qDebug() << QString("网络连接错误，错误计数: %1").arg(m_networkErrorCount);
            break;
            
        case QAbstractSocket::NetworkError:
        case QAbstractSocket::UnknownSocketError:
            // 网络层错误，记录但不重连
            qDebug() << "网络层错误发生";
            break;
            
        default:
            // 其他错误，只记录不处理
            break;
    }
    
    emit errorOccurred(errorString);
}

void RobotClient::onHeartbeatTimeout()
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    qDebug() << QString("机器人心跳超时: %1 (SN: %2)，当前时间: %3").arg(getClientAddress()).arg(m_robotSN).arg(currentTime);
    
    // 如果设备未注册，不触发重连机制
    if (!m_isRegistered) {
        qDebug() << "未注册设备心跳超时，不触发重连机制";
        return;
    }
    
    // 更新心跳超时状态
    m_heartbeatState.lastTimeoutTime = currentTime;
    m_heartbeatState.consecutiveTimeouts++;
    
    qDebug() << QString("心跳超时次数: %1").arg(m_heartbeatState.consecutiveTimeouts);
    
    // 只有连续多次确认的心跳丢失才触发断开
        if (m_heartbeatState.consecutiveTimeouts >= 2) {
            qDebug() << QString("确认心跳丢失，连续超时次数: %1").arg(m_heartbeatState.consecutiveTimeouts);
            
            // 记录心跳超时断开日志
            DisconnectLogger::instance()->logHeartbeatTimeout(
                m_robotSN,
                getClientAddress(),
                m_heartbeatState.consecutiveTimeouts,
                QDateTime::currentMSecsSinceEpoch() - m_connectionStartTime,
                m_heartbeatState.consecutiveTimeouts
            );
            
            // 重置连接状态
            m_isRegistered = false;
            m_robotSN.clear();
            stopHeartbeatTimer();
            stopRegisterTimeoutTimer();
            
            // 发送断开连接信号
            emit disconnected();
            
            qDebug() << "心跳超时导致连接断开，等待下位机重新发起连接请求";
        } else {
            qDebug() << QString("等待确认心跳丢失，当前连续超时次数: %1").arg(m_heartbeatState.consecutiveTimeouts);
            // 重新启动心跳定时器，给更多时间等待心跳
            startHeartbeatTimer();
        }
}

void RobotClient::processMessage(const QJsonObject &message)
{
    QString type = message.value("type").toString();
    // 减少不必要的调试日志输出
    // qDebug() << "RobotClient::processMessage() 处理消息类型:" << type;
    
    if (type == "register") {
        handleRegistration(message);
    } else if (type == "data") {
        handleDataUpdate(message);
    } else if (type == "heartbeat") {
        handleHeartbeat(message);
    } else if (type == "rtsp_urls") {
        handleRTSPUrls(message);
    } else if (type == "rtsp_urls_response") {
        // 添加对rtsp_urls_response类型的处理
        handleRTSPUrls(message);
    } else if (type == "request_rtsp_urls") {
        handleRequestRTSPUrls(message);
    } else if (type == "time_sync") {
        handleTimeSync(message);
    } else if (type == "time_sync_ack") {
        handleTimeSyncAck(message);
    } else if (message.contains("longitude") && message.contains("latitude")) {
        qDebug() << "RobotClient::processMessage() 检测到新格式定位数据，机器人SN:" << m_robotSN
        << "经度:" << message.value("longitude").toDouble()
        << "纬度:" << message.value("latitude").toDouble();
        // 当作数据更新处理，转发到RobotManager
        handleDataUpdate(message);
    } else {
        qDebug() << "RobotClient::processMessage() 未知消息类型:" << type;
    }
}

void RobotClient::handleRegistration(const QJsonObject &message)
{
    QString sn = message.value("sn").toString();
    QString ip = message.value("ip").toString();
    int port = message.value("port").toInt();
    
    // 减少不必要的调试日志输出
    // qDebug() << QString("RobotClient::handleRegistration() 处理注册请求: SN=%1, IP=%2, Port=%3").arg(sn).arg(ip).arg(port);
    
    // 验证IP地址有效性
    if (ip.isEmpty() || ip == ":0" || ip == "0.0.0.0") {
        // 如果消息中没有提供有效的IP地址，使用socket的peerAddress
        ip = getClientAddress();
        port = getClientPort();
        
        // 再次验证从socket获取的IP地址是否有效
        if (ip.isEmpty() || ip == ":0" || ip == "0.0.0.0") {
            QString socketAddress = m_socket->peerAddress().toString();
            int socketPort = m_socket->peerPort();
            qDebug() << QString("注册失败：机器人IP地址无效，Socket地址: %1:%2").arg(socketAddress).arg(socketPort);
            // 发送注册失败响应
            QJsonObject response;
            response["type"] = "register_ack";
            response["status"] = "failed";
            response["message"] = "IP地址无效";
            sendMessage(response);
            return;
        }
    }
    
    // 更新缓存的客户端地址
    m_cachedClientAddress = ip;
    
    // 检查是否已经注册
    if (m_isRegistered) {
        // 减少不必要的调试日志输出
        // qDebug() << QString("警告：机器人 %1 已经注册，忽略重复注册请求").arg(sn);
        // 发送已注册确认，确保下位机知道注册成功
        QJsonObject response;
        response["type"] = "register_ack";
        response["status"] = "success";
        response["message"] = "已注册";
        response["sn"] = sn;
        sendMessage(response);
        return;
    }
    
    m_robotSN = sn;
    m_isRegistered = true;
    
    // 停止注册超时定时器
    stopRegisterTimeoutTimer();
    
    qDebug() << QString("机器人注册成功: SN=%1, IP=%2:%3").arg(sn).arg(ip).arg(port);
    
    // 发送注册确认，确保下位机知道注册成功
    QJsonObject response;
    response["type"] = "register_ack";
    response["status"] = "success";
    response["message"] = "注册成功";
    response["sn"] = sn;
    sendMessage(response);
    
    emit registered(sn);
}

void RobotClient::handleDataUpdate(const QJsonObject &message)
{
    qDebug() << "RobotClient::handleDataUpdate() 处理数据更新，机器人是否已注册:" << m_isRegistered;
    
    if (!m_isRegistered) {
        qDebug() << "未注册的机器人尝试发送数据";
        return;
    }
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    qDebug() << "RobotClient::handleDataUpdate() 发射dataReceived信号，机器人SN:" << m_robotSN;
    emit dataReceived(m_robotSN, message);
}

void RobotClient::handleHeartbeat(const QJsonObject &message)
{
    // 如果设备未注册，不处理心跳消息
    if (!m_isRegistered) {
        qDebug() << "未注册设备发送心跳消息，忽略处理";
        return;
    }
    
    // 获取心跳时间戳
    qint64 timestamp = message.value("timestamp").toVariant().toLongLong();
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    
    // 判断时间戳单位并进行转换
    qint64 timestampMs = timestamp;
    if (timestamp < 10000000000) {  // 如果小于100亿，可能是秒级时间戳
        timestampMs = timestamp * 1000;  // 转换为毫秒
        qDebug() << "检测到秒级时间戳，转换为毫秒:" << timestamp << "->" << timestampMs;
    }
    
    // 检查时间戳有效性 - 更严格的检查
    if (timestampMs <= 0) {
        qWarning() << "收到无效时间戳（<=0）:" << timestampMs;
        return; // 不处理异常时间戳
    }
    
    // 检查时间戳是否在合理范围内（当前时间±1小时）
    qint64 timeDiff = qAbs(currentTime - timestampMs);
    if (timeDiff > 3600000) {  // 1小时 = 3600000毫秒
        qWarning() << "收到异常时间戳，与系统时间差异过大:" << timestampMs << "差异:" << timeDiff << "ms";
        return; // 不处理异常时间戳
    }
    
    // 计算延迟（毫秒）
    qint64 delay = timeDiff;
    
    qDebug() << QString("RobotClient::handleHeartbeat() 处理心跳消息，时间戳: %1，当前时间: %2，延迟: %3ms")
                .arg(timestampMs).arg(currentTime).arg(delay);
    
    // 检查延迟是否异常（超过5分钟）
    if (delay > 300000) {  // 5分钟 = 300000毫秒
        qWarning() << "心跳延迟异常，可能网络延迟或时间基准不一致，延迟:" << delay << "ms";
        // 继续处理，但记录警告
    }
    
    // 更新最后心跳接收时间
    m_heartbeatState.lastReceivedTime = currentTime;
    m_heartbeatState.consecutiveTimeouts = 0;  // 重置超时计数
    m_heartbeatState.missedHeartbeats = 0;     // 重置错失心跳计数
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    // 发送心跳响应，确保下位机知道心跳已被接收
    QJsonObject response;
    response["type"] = "heartbeat_ack";
    response["timestamp"] = currentTime;
    sendMessage(response);
    
    // 【关键优化】心跳隔离：心跳只更新内存状态，不直接操作数据库
    // 移除数据库更新调用，降低I/O延迟
    // emit dataReceived(m_robotSN, message);
    
    // 发送专门的内存状态更新信号
    emit heartbeatReceived(m_robotSN, message);
}

// 处理RTSP地址响应
void RobotClient::handleRTSPUrls(const QJsonObject &message)
{
    qDebug() << "RobotClient::handleRTSPUrls() 处理RTSP地址响应，机器人SN:" << m_robotSN;
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    // 发送RTSP地址响应到RobotManager
    qDebug() << "RobotClient::handleRTSPUrls() 发射dataReceived信号，机器人SN:" << m_robotSN;
    emit dataReceived(m_robotSN, message);
}

// 处理RTSP地址请求
void RobotClient::handleRequestRTSPUrls(const QJsonObject &message)
{
    // 减少不必要的调试日志输出
    // qDebug() << "RobotClient::handleRequestRTSPUrls() 处理RTSP地址请求，机器人SN:" << m_robotSN;
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    // 发送RTSP地址响应
    QJsonObject response;
    response["type"] = "rtsp_urls_response";
    response["timestamp"] = QDateTime::currentMSecsSinceEpoch();
    
    // 添加RTSP URL数组（简化为实际需要的URL数量）
    QJsonArray rtspUrls;
    rtspUrls.append("rtsp://192.168.126.182:8554/cam1");
    response["rtsp_urls"] = rtspUrls;
    response["stream_count"] = 1;
    
    // 添加调试输出，显示将要发送的RTSP URL
    // qDebug() << "RobotClient::handleRequestRTSPUrls() 准备发送的RTSP URL: rtsp://192.168.126.182:8554/cam1";
    // qDebug() << "RobotClient::handleRequestRTSPUrls() 发送的完整响应数据:" << QJsonDocument(response).toJson(QJsonDocument::Compact);
    
    sendMessage(response);
    
    // qDebug() << "RobotClient::handleRequestRTSPUrls() 已发送RTSP地址响应";
}

// 处理时间同步请求
void RobotClient::handleTimeSync(const QJsonObject &message)
{
    qDebug() << "RobotClient::handleTimeSync() 处理时间同步请求，机器人SN:" << m_robotSN;
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    // 获取时间戳
    qint64 timestamp = message["timestamp"].toVariant().toLongLong();
    QString syncId = message["sync_id"].toString();
    
    // 在实际设备中，这里应该设置系统时间
    // 由于这是模拟环境，我们只记录日志
    qDebug() << QString("接收到时间同步请求: timestamp=%1, sync_id=%2").arg(timestamp).arg(syncId);
    
    // 发送时间同步响应
    QJsonObject response;
    response["type"] = "time_sync_ack";
    response["timestamp"] = timestamp;  // 回传时间戳
    response["sync_id"] = syncId;
    response["status"] = "success";
    response["message"] = "时间同步成功";
    
    sendMessage(response);
    
    qDebug() << "RobotClient::handleTimeSync() 已发送时间同步响应";
}

void RobotClient::handleTimeSyncAck(const QJsonObject &message)
{
    qDebug() << "RobotClient::handleTimeSyncAck() 处理时间同步响应，机器人SN:" << m_robotSN;
    
    // 重置心跳定时器和网络错误计数
    startHeartbeatTimer();
    m_networkErrorCount = 0;
    
    // 获取时间戳和同步ID
    qint64 timestamp = message["timestamp"].toVariant().toLongLong();
    QString syncId = message["sync_id"].toString();
    QString status = message["status"].toString();
    QString messageText = message["message"].toString();
    
    qDebug() << QString("接收到时间同步响应: timestamp=%1, sync_id=%2, status=%3, message=%4")
                .arg(timestamp).arg(syncId).arg(status).arg(messageText);
    
    // 可以在这里添加时间同步成功的处理逻辑
    if (status == "success") {
        qDebug() << "时间同步成功确认";
    } else {
        qWarning() << "时间同步失败:" << messageText;
    }
}

void RobotClient::startHeartbeatTimer()
{
    m_heartbeatTimer->start();
}

void RobotClient::stopHeartbeatTimer()
{
    m_heartbeatTimer->stop();
}

void RobotClient::startNetworkCheckTimer()
{
    // 不启动网络检查定时器，确保程序稳定运行
    // m_networkCheckTimer->start();
}

void RobotClient::stopNetworkCheckTimer()
{
    // 不停止网络检查定时器，确保程序稳定运行
    // m_networkCheckTimer->stop();
}

void RobotClient::startRegisterTimeoutTimer()
{
    // 仅对未注册设备启动注册超时检查
    if (!m_isRegistered) {
        m_registerTimeoutTimer->start();
        qDebug() << "启动注册超时定时器，超时时间：" << REGISTER_TIMEOUT << "毫秒";
    }
}

void RobotClient::stopRegisterTimeoutTimer()
{
    m_registerTimeoutTimer->stop();
}

void RobotClient::onRegisterTimeout()
{
    // 如果设备仍未注册，则断开连接
    if (!m_isRegistered) {
        qDebug() << QString("设备注册超时，断开连接: %1").arg(getClientAddress());
        
        // 记录注册超时断开日志
        DisconnectLogger::instance()->logRegisterTimeout(
                getClientAddress(),
                QDateTime::currentMSecsSinceEpoch() - m_connectionStartTime
            );
        
        disconnectFromHost();
    }
}

void RobotClient::checkNetworkStatus()
{
    // 移除socket状态检查，始终认为连接正常，确保程序稳定运行
    /*
    // 检查socket状态
    QAbstractSocket::SocketState state = m_socket->state();
    
    // 如果socket未连接，增加错误计数
    if (state != QAbstractSocket::ConnectedState) {
        m_networkErrorCount++;
        qDebug() << QString("网络状态检查: 连接状态异常，错误计数: %1").arg(m_networkErrorCount);
    } else {
        // 如果连接正常，重置错误计数
        if (m_networkErrorCount > 0) {
            qDebug() << QString("网络连接恢复正常: %1 (SN: %2)").arg(getClientAddress()).arg(m_robotSN);
            m_networkErrorCount = 0;
        }
    }
    */
    
    // 检查socket是否有待发送的数据
    if (m_socket->bytesToWrite() > 0) {
        qDebug() << QString("网络状态检查: 有待发送数据 %1 字节").arg(m_socket->bytesToWrite());
    }
}

QString RobotClient::getCurrentLogFileName()
{
    // 获取当前日期并生成日志文件名
    QString currentDate = QDateTime::currentDateTime().toString("yyyy-MM-dd");
    QString logDir = "logs";  // 日志目录
    
    // 确保日志目录存在
    QDir dir;
    if (!dir.exists(logDir)) {
        dir.mkpath(logDir);
    }
    
    return QString("%1/robot_packets_%2.log").arg(logDir).arg(currentDate);
}

void RobotClient::initializePacketLog()
{
    // 获取当前日志文件名
    m_currentLogFileName = getCurrentLogFileName();
    
    // 创建日志文件对象
    m_packetLog = new QFile(m_currentLogFileName);
    
    // 如果文件不存在，创建并添加文件头
    if (!m_packetLog->exists()) {
        if (m_packetLog->open(QIODevice::WriteOnly | QIODevice::Append)) {
            QTextStream out(m_packetLog);
            out << "=== Robot Packet Log ===\n";
            out << "Log Start Time: " << QDateTime::currentDateTime().toString(Qt::ISODate) << "\n";
            out << "========================================\n";
            m_packetLog->close();
        }
    }
}

void RobotClient::logPacket(const QByteArray &data)
{
    // 检查是否需要创建新的日志文件（跨天情况）
    QString newLogFileName = getCurrentLogFileName();
    if (newLogFileName != m_currentLogFileName) {
        // 关闭当前日志文件
        if (m_packetLog && m_packetLog->isOpen()) {
            m_packetLog->close();
        }
        delete m_packetLog;
        
        // 更新日志文件名并重新初始化
        m_currentLogFileName = newLogFileName;
        m_packetLog = new QFile(m_currentLogFileName);
    }
    
    // 将日志数据添加到队列中，实现异步写入
    QMutexLocker locker(&m_logMutex);
    m_logQueue.enqueue(data);
}

void RobotClient::flushLogQueue()
{
    if (m_logQueue.isEmpty()) {
        return;
    }
    
    // 批量写入日志，避免频繁的文件I/O操作
    QMutexLocker locker(&m_logMutex);
    if (m_packetLog->open(QIODevice::WriteOnly | QIODevice::Append)) {
        QTextStream out(m_packetLog);
        while (!m_logQueue.isEmpty()) {
            QByteArray data = m_logQueue.dequeue();
            out << "Timestamp: " << QDateTime::currentDateTime().toString(Qt::ISODateWithMs) << "\n";
            out << "Robot SN: " << m_robotSN << "\n";
            out << "Raw Data: " << data << "\n";
            out << "----------------------------------------\n";
        }
        m_packetLog->close();
    }
}

// 添加一个辅助函数来将socket状态转换为可读的字符串
QString RobotClient::socketStateToString(QAbstractSocket::SocketState state) const
{
    switch (state) {
    case QAbstractSocket::UnconnectedState:
        return "Unconnected";
    case QAbstractSocket::HostLookupState:
        return "HostLookup";
    case QAbstractSocket::ConnectingState:
        return "Connecting";
    case QAbstractSocket::ConnectedState:
        return "Connected";
    case QAbstractSocket::BoundState:
        return "Bound";
    case QAbstractSocket::ListeningState:
        return "Listening";
    case QAbstractSocket::ClosingState:
        return "Closing";
    default:
        return "Unknown";
    }
}
